<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class FavoriteController extends Controller
{

    public function __construct(Request $request)
    {
        //再同步情况调用中间件
        if (!$request->expectsJson()) {
            $this->middleware('auth');

        }
    }

    public function make(Request $request, $model, $id)
    {

        $model = $this->model();

        //异步json和同步方法重写，通过$request->expectsJson()判定是否位json请求
        if ($request->expectsJson()) {
            return $this->asyncMake($model, $id);
        } else {
            //通过中间件验证是否登录，同步情况可以使用，但是在json异步情况中间件不起作用。
            return $this->syncMake($model, $id);
        }

    }

    public function asyncMake($model, $id)
    {
        $click = request()->input('click');
        //$click,前台vue按钮 选中状态status,
        if (Auth::check() && $click) {
            $model->favorite();
            $route = false;
        } else {
            $url = request()->input('preUrl');
            session(['preUrl' => $url]);
            $route = route('login');
        }

        return response()->json(['isFavorite' => $model->isFavorite, 'favoriteCount' => $model->favorite_count, 'route' => $route]);
    }

    public function syncMake($model, $id)
    {

        $model->favorite();
        return back();
    }

    public function model()
    {
        $class = 'Modules\Edu\Entities\\' . request()->model;
        return app($class)->find(request()->id);
    }
}
